import { defHttp } from '/@/utils/http/axios';
import { LoginParams, LoginResultModel, GetUserInfoModel } from './model/userModel';
import { AesEncryption } from '/@/utils/cipher';

import { ContentTypeEnum } from '/@/enums/httpEnum';

import { ErrorMessageMode } from '/#/axios';

enum Api {
  Login = '/auth/oauth2/token',
  Logout = '/auth/token/logout',
  GetUserInfo = '/admin/user/info',
  GetPermCode = '/getPermCode',
  TestRetry = '/testRetry',
  TenantList = '/admin/tenant/public/',
  Publicinfo = '/admin/tenant/publicinfo/',
  EditUserProfilePassWord = '/admin/user/updateOwnPassword',
}
const encPassword = 'pigxpigxpigxpigx'; // 前后端数据传输的密钥

const encryption = new AesEncryption({
  key: encPassword,
  iv: encPassword,
  mode: 'CFB',
  padding: 'NoPadding',
});

/**
 * @description: user login api
 */
export function loginApi(data: LoginParams, mode: ErrorMessageMode = 'modal') {
  data.password = encryption.encryptByAES(data.password);

  return defHttp.post<LoginResultModel>(
    {
      url: Api.Login,
      params: {
        randomStr: 'blockPuzzle',
        grant_type: 'password',
        scope: 'server',
      },
      data,
      headers: {
        'Content-Type': ContentTypeEnum.FORM_URLENCODED,
        Authorization: 'Basic cGlnOnBpZw==',
      },
    },
    {
      errorMessageMode: mode,
      isTransformResponse: false,
    },
  );
}

export function getTenantList(domain: string) {
  return defHttp.get<any>({ url: Api.TenantList + domain });
}

export function getPublicinfoApi(domain: string) {
  return defHttp.get<any>({ url: Api.Publicinfo + domain });
}

/**
 * @description: getUserInfo
 */
export function getUserInfo() {
  return defHttp.get<GetUserInfoModel>({ url: Api.GetUserInfo }, { errorMessageMode: 'none' });
}

export function getPermCode() {
  return defHttp.get<string[]>({ url: Api.GetPermCode });
}

export function doLogout() {
  return defHttp.post({ url: Api.Logout });
}

export function testRetry() {
  return defHttp.get(
    { url: Api.TestRetry },
    {
      retryRequest: {
        isOpenRetry: true,
        count: 5,
        waitTime: 1000,
      },
    },
  );
}

export const EditUserProfilePassWord = (params: { password: string; newPassword: string }) => {
  params.password = encryption.encryptByAES(params.password);
  params.newPassword = encryption.encryptByAES(params.newPassword);

  return defHttp.post({
    url: Api.EditUserProfilePassWord,
    params,
  });
};
